package com.firebird.app.fekpsl.ui.activity.me

import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.firebird.app.fekpsl.R
import com.firebird.app.fekpsl.android.db.City
import com.firebird.app.fekpsl.android.db.County
import com.firebird.app.fekpsl.android.db.Province
import com.firebird.app.fekpsl.android.util.HttpUtil
import com.firebird.app.fekpsl.android.util.Utility
import com.firebird.app.fekpsl.base.BaseMvpActivity
import com.firebird.app.fekpsl.constant.Constant
import com.firebird.app.fekpsl.ext.showToast
import com.firebird.app.fekpsl.mvp.me.AreaContract
import com.firebird.app.fekpsl.mvp.me.AreaPresenter
import com.firebird.app.fekpsl.utils.Preference
import kotlinx.android.synthetic.main.me_update_area.*
import kotlinx.android.synthetic.main.me_update_real_name.*
import kotlinx.android.synthetic.main.toolbar.*
import org.litepal.LitePal

import java.io.IOException
import java.util.ArrayList

import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response

class UpdateAreaActivity : BaseMvpActivity<AreaContract.View, AreaContract.Presenter>(), AreaContract.View {
    private var pf_area:String by Preference(Constant.AREA_KEY, "")
    private var pf_uuid:String by Preference(Constant.UUID_KEY, "")

    private val adapter by lazy {
        ArrayAdapter(this@UpdateAreaActivity, android.R.layout.simple_list_item_1, dataList)
    }
    private val dataList = ArrayList<String>()
    private var provinceList: List<Province>? = null
    private var cityList: List<City>? = null
    private var selectedProvince: Province? = null
    private var selectedCity: City? = null
    private var currentLevel: Int = 0

    override fun createPresenter(): AreaContract.Presenter = AreaPresenter()

    private val mDialog by lazy {
        // DialogUtil.getWaitDialog(this, getString(R.string.save_ing))
    }

    override fun showLoading() {
        // mDialog.show()
    }

    override fun hideLoading() {
        // mDialog.dismiss()
    }

    override fun updateAreaSuccess(success: Boolean) {
        if(success){
            pf_area=et_me_real_name.text.toString()
            finish()
        }else{
            // showToast(getString(R.string.me_save_fail))
        }
    }
    //http://ip-api.com/json/25.191.200.34?lang=zh-CN
    override fun attachLayoutRes(): Int = R.layout.me_update_area

    override fun initData() {
    }

    override fun initView() {
        super.initView()

        toolbar.run {
            title = resources.getString(R.string.me_update_area)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }

        lv_area.adapter = adapter
        lv_area.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            when (currentLevel) {
                LEVEL_PROVINCE -> {
                    selectedProvince = provinceList!![position]
                    queryCities()
                }
                LEVEL_CITY -> {
                    selectedCity = cityList!![position]
                    pf_area=selectedProvince!!.provinceName.toString()+"."+selectedCity!!.cityName.toString()
                }
                else -> {}
            }
        }
              //  tv_area_title.setText(pf_area)
       // btn_save.setOnClickListener(onClickListener)

        back_button.setOnClickListener {
            when (currentLevel) {
                /*
                LEVEL_COUNTY -> {
                    queryCities()
                }*/
                LEVEL_CITY -> {
                    queryProvinces()
                }
                else -> {}
            }
        }
        queryProvinces()
    }

    private fun queryProvinces() {
        tv_area_name.setText(R.string.area_china)
        back_button.visibility = View.GONE
        provinceList = LitePal.findAll(Province::class.java)

        provinceList?.let {
            if (it.isNotEmpty()) {
                dataList.clear()
                it.map {
                    dataList.add(it.provinceName!!)
                }
                adapter.notifyDataSetChanged()
                lv_area.setSelection(0)
                currentLevel = LEVEL_PROVINCE
                return
            }
        }
        queryFromServer(HttpUtil.China, "province")
    }

    private fun queryCities() {
        tv_area_name.text = selectedProvince!!.provinceName
        back_button.visibility = View.VISIBLE
        cityList = LitePal.where("provinceid = ?", selectedProvince!!.id.toString())
                .find(City::class.java)

        cityList?.let {
            if (it.isNotEmpty()) {
                dataList.clear()
                it.map {
                    dataList.add(it.cityName!!)
                }
                adapter.notifyDataSetChanged()
                lv_area.setSelection(0)
                currentLevel = LEVEL_CITY
                return
            }
        }
        val provinceCode = selectedProvince!!.provinceCode
        val address = "${HttpUtil.China}/$provinceCode"
        queryFromServer(address, "city")
    }

    private fun queryFromServer(address: String, type: String) {
        HttpUtil.sendOkHttpRequest(address, object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                val responseText = response.body()!!.string()
                var result = false
                when (type) {
                    "province" -> {
                        result = Utility.handleProvinceResponse(responseText)
                    }
                    "city" -> {
                        result = Utility.handleCityResponse(responseText, selectedProvince!!.id)
                    }
                    /*
                    "county" -> {
                        result = Utility.handleCountyResponse(responseText, selectedCity!!.id)
                    }*/
                }
                if (result) {
                    this@UpdateAreaActivity?.runOnUiThread(Runnable {
                        when (type) {
                            "province" -> {
                                queryProvinces()
                            }
                            "city" -> {
                                queryCities()
                            }
                        }
                    })
                }
            }
            override fun onFailure(call: Call, e: IOException) {
                this@UpdateAreaActivity?.runOnUiThread(Runnable {
                    showToast( "load failed")
                })
            }
        })
    }

    override fun start() {
    }

    /**
     * OnClickListener
     */
    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.btn_save -> {
                updateArea()
            }
        }
    }
    private fun updateArea() {
        if (validate()) {
            mPresenter?.updateArea(pf_uuid, tv_area_name.text.toString()
            )
        }
    }
    /**
     * check data
     */
    private fun validate(): Boolean {
        var valid = true
        val areaName: String = tv_area_name.text.toString()

        if (areaName.isEmpty()) {
            tv_area_name.error = getString(R.string.me_area_not_empty)
            valid = false
        }
        return valid
    }

    companion object {
        private val TAG = "ChooseAreaFragment"
        val LEVEL_PROVINCE = 0
        val LEVEL_CITY = 1
        //val LEVEL_COUNTY = 2
    }


}